<?php
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'Base.php');

class Sys extends Base
{
    private static $app;
    private static $config;
    private $controller, $db;
    private $error='';
    private $scripts=array();

    private function __construct()
    {
        session_start();
        $this->loadClasses();
        self::$config=$this->loadClass('Config')->getConfig();
    }

    private function __clone() {}

    public function getConfig()
    {
        return self::$config;
    }

    public function setController($value)
    {
        if(is_object($value)) $this->controller=$value;
    }

    public function getController()
    {
        return $this->controller;
    }

    public function setDb($value)
    {
        if(is_object($value)) $this->db=$value;
    }

    public function getDb()
    {
        return $this->db;
    }

    public static function app()
    {
        if(self::$app===NULL) return self::$app=new self();
        else return self::$app;
    }

    public function run()
    {
        $router=$this->loadClass('Router');
        $this->setAppConfig();
        $router->run();
        if(Sys::app()->config->mode=='test') echo $this->error;
    }

    public static function show($something,$var_dump=false)
    {
        echo '<pre>';
        if(!$var_dump) print_r($something);
        else var_dump($something);
        exit;
    }

    public function getError()
    {
        return $this->error;
    }

    public function setError($text)
    {
        if($text && is_string($text)) $this->error.=$text.'<br/>';
    }

    public function loadClass($class)
    {
        return Loader::loadClass($class);
    }

    public function loadModel($model)
    {
        return Loader::loadModel($model);
    }

    public function loadView($file)
    {
        return Loader::loadClass($file);
    }

    public function setScripts($script)
    {
        if(!is_file(str_replace(BASEURL,BASE_DIR,$script))) return;
        if(!in_array($script,$this->scripts)) $this->scripts[]=$script;
        return;
    }

    public function getScripts()
    {
        $scripts=$this->scripts;
        $this->scripts=array();
        return $scripts;
    }

    private function loadClasses()
    {
        foreach(glob(dirname(__FILE__).DIRECTORY_SEPARATOR.'system'.DIRECTORY_SEPARATOR.'*.php') as $classFile){
            require_once($classFile);
        }
    }

    private function setAppConfig()
    {
        $this->controller->theme=$this->config->theme;
        $this->title=$this->config->title;

        if(self::$config->db){
            $this->db=new DB($this->config->db->connectionString,$this->config->db->user,$this->config->db->password);
        }else{
            $this->db=false;
        }
    }

    public function __destruct()
    {
        $this->db=null;
    }
}